package com.zhudi.filter;

import cn.hutool.core.util.StrUtil;
import common.zhudi.expection.BusinessException;
import common.zhudi.service.InnerUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Objects;

import static common.zhudi.commen.ErrorCode.NO_AUTH;
import static common.zhudi.commen.ErrorCode.PARAMS_ERROR;


@Component
@Slf4j
public class CustomGlobalFilter implements GlobalFilter, Ordered {

    @DubboReference
    private InnerUserService userService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("************************用户鉴权*****************************");
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders headers = request.getHeaders();
        // 1. 接受用户发送的 ak、
        String authorization = Objects.requireNonNull(headers.get("authorization")).get(0);
        if (authorization==null){
            throw new BusinessException(NO_AUTH);
        }
        //todo：解决这个过滤器调用两次的问题
        List<String> stringList = StrUtil.split(authorization, "/");
        if (stringList.size()<3){
            throw new BusinessException(PARAMS_ERROR,"参数不足，身份验证失败");
        }
        String accessKey = stringList.get(0);
        String sendTime = stringList.get(1);
        String signature = stringList.get(2);
        //2. 检查时间是否相差超过 5 分钟
        long current = System.currentTimeMillis();
        if ((current-Long.parseLong(sendTime))/60000>5){
            return null;
        }
        boolean isLegal = userService.checkAuthorization(accessKey, sendTime, signature);
        log.info("请求的 accessKey = "+accessKey);
        log.info("请求的 sendTime = "+sendTime);
        log.info("请求的 结果 = "+isLegal);
        log.info("************************用户鉴权结束*****************************\n");
        if (!isLegal){
            throw new BusinessException(NO_AUTH);
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }

}

